package com.gigi.service.manual;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.alibaba.cola.dto.MultiResponse;
import com.alibaba.cola.dto.Response;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gigi.entity.AskForLeaveEntity;
import com.gigi.entity.SignInRecordEntity;
import com.gigi.enums.*;
import com.gigi.mapper.manual.AskForLeaveManualMapper;
import com.gigi.model.AskForLeaveDO;
import com.gigi.model.ExamineRequest;
import com.gigi.model.ListExamineRequest;
import com.gigi.service.generated.AskForLeaveService;
import com.gigi.service.generated.SignInRecordService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

@Service
public class AskForLeaveManageService {

    private final AskForLeaveService askForLeaveService;
    private final AskForLeaveManualMapper askForLeaveManualMapper;
    private final SignInRecordManageService signInRecordManageService;
    private final SignInRecordService signInRecordService;

    public AskForLeaveManageService(AskForLeaveService askForLeaveService, AskForLeaveManualMapper askForLeaveManualMapper,
                                    SignInRecordManageService signInRecordManageService, SignInRecordService signInRecordService) {
        this.askForLeaveService = askForLeaveService;
        this.askForLeaveManualMapper = askForLeaveManualMapper;
        this.signInRecordManageService = signInRecordManageService;
        this.signInRecordService = signInRecordService;
    }

    /**
     * 新增接口
     *
     * @param request
     * @return
     */
    public Response insert(AskForLeaveDO request) {

        LambdaQueryWrapper<AskForLeaveEntity> wrapper = new LambdaQueryWrapper<AskForLeaveEntity>()
                .eq(AskForLeaveEntity::getSignInId, request.getSignInId())
                .eq(AskForLeaveEntity::getUserId, request.getUserId())
                .orderByDesc(AskForLeaveEntity::getId);
        List<AskForLeaveEntity> list = askForLeaveService.list(wrapper);

        // 已有待审核 or 审核通过的申请，无需新增
        if (CollUtil.isNotEmpty(list)) {

            if (ExamineStateEnum.UN_CHECK.getCode().equals(list.get(0).getState())) {
                return Response.buildFailure(ErrorCodeEnum.UN_CHECK.getErrCode(), ErrorCodeEnum.UN_CHECK.getErrDesc());
            }

            if (ExamineStateEnum.PASS.getCode().equals(list.get(0).getState())) {
                return Response.buildFailure(ErrorCodeEnum.PASS.getErrCode(), ErrorCodeEnum.PASS.getErrDesc());
            }
        }

        AskForLeaveEntity entity = new AskForLeaveEntity();
        entity.setUserId(request.getUserId());
        entity.setType(request.getAskForType());
        entity.setReason(request.getReason());
        entity.setSignInId(request.getSignInId());
        if (!askForLeaveService.save(entity)) {
            return Response.buildFailure(ErrorCodeEnum.SAVE_FAILED.getErrCode(), ErrorCodeEnum.SAVE_FAILED.getErrDesc());
        }
        return Response.buildSuccess();
    }

    /**
     * 学生请假申请列表接口
     *
     * @param request
     * @return
     */
    public MultiResponse<AskForLeaveDO> listForStudent(ListExamineRequest request) {
        List<AskForLeaveDO> askForLeaveDOS = askForLeaveManualMapper.listForStudent(request.getUserId());
        if (CollUtil.isNotEmpty(askForLeaveDOS)) {
            askForLeaveDOS.forEach(e -> {
                e.setTypeDesc(SignInTypeEnum.getEnumByCode(e.getType()).getDesc());
            });
        }
        return MultiResponse.of(askForLeaveDOS, askForLeaveDOS.size());
    }

    /**
     * 老师请假申请列表接口
     *
     * @param request
     * @return
     */
    public MultiResponse<AskForLeaveDO> listForTeacher(ListExamineRequest request) {
        List<AskForLeaveDO> askForLeaveDOS = askForLeaveManualMapper.listForTeacher(request.getUserId());
        if (CollUtil.isNotEmpty(askForLeaveDOS)) {
            askForLeaveDOS.forEach(e -> {
                e.setTypeDesc(SignInTypeEnum.getEnumByCode(e.getType()).getDesc());
                e.setStartTimeStr(DateUtil.format(e.getStartTime(), DatePattern.NORM_DATETIME_PATTERN));
            });
        }
        return MultiResponse.of(askForLeaveDOS, askForLeaveDOS.size());
    }

    /**
     * 审批接口
     *
     * @param request
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public Response examine(ExamineRequest request) {
        // 改审核状态
        AskForLeaveEntity oldModel = askForLeaveService.getById(request.getId());
        AskForLeaveEntity entity = new AskForLeaveEntity();
        entity.setId(oldModel.getId());
        entity.setState(request.getState());
        askForLeaveService.updateById(entity);

        // 如果通过，改考勤状态为请假
        if (YesOrNoEnum.YES.getCode().equals(request.getState())) {
            editRecordState(oldModel.getUserId(), oldModel.getSignInId(), SignInRecordStateEnum.ASK_FOR_LEAVE.getCode());
        }
        return Response.buildSuccess();
    }

    // 修改考勤状态
    public void editRecordState(Long userId, Long signId, Integer state) {
        LambdaQueryWrapper<SignInRecordEntity> wrapper = new LambdaQueryWrapper<SignInRecordEntity>()
                .eq(SignInRecordEntity::getSignInId, signId)
                .eq(SignInRecordEntity::getUserId, userId);
        SignInRecordEntity oldModel = signInRecordService.getOne(wrapper, false);

        SignInRecordEntity target = new SignInRecordEntity();
        target.setId(oldModel.getId());
        target.setState(state);
        signInRecordService.updateById(target);
    }


}
